package org.siberia.server.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.siberia.client.bean.UserDTO;
import org.siberia.server.converter.UserConverter;
import org.siberia.server.model.User;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class UserServiceImpl extends RemoteServiceServlet implements org.siberia.client.service.UserService
{
	public UserDTO getUserByName(String name)
	{
		UserDTO result = null;
		
		User _user = User.findUserByName(name);
		
		if ( _user != null )
		{
			result = UserConverter.convert(_user);
		}
		
		return result;
	}
	
	public void createUser(UserDTO user)
	{
		User _user = UserConverter.convert(user);
		_user.persist();
	}

	public List<UserDTO> findAll()
	{
		List<UserDTO> result = null;
		
		List<User> users = User.findAll();
		
		if ( ! users.isEmpty() )
		{
			Iterator<User> it = users.iterator();
			
			while(it.hasNext())
			{
				User currentUser = it.next();
				
				if ( currentUser != null )
				{
					if ( result == null )
					{
						result = new ArrayList<UserDTO>(users.size());
					}
					
					UserDTO dto = UserConverter.convert(currentUser);
					
					if ( dto != null )
					{
						result.add(dto);
					}
				}
			}
		}
		if ( result == null )
		{
			result = Collections.<UserDTO>emptyList();
		}
		
		return result;
	}
	
	public void deleteAll()
	{
		User.deleteAll();
	}
}
